package com.xiaomi.shwx.common.util;


import io.jsonwebtoken.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lei
 * @description
 * @date 2024/5/22 19:21
 */
public class JwtUtil {

    private static final String jwtToken = "123456Mszlu!@#$$";
    private static final long time = 24 * 60 * 60 * 60 * 1000;

    /**
     * 生成jwtToken
     * 使用Hs256算法
     * @param userId
     * @return
     */
    public static String createToken(Long userId) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", userId);
        JwtBuilder jwtBuilder = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, jwtToken)
                .setClaims(claims)
                .setIssuedAt(new Date())
                //设置过期时间
                .setExpiration(new Date(System.currentTimeMillis() +time));
        String token=jwtBuilder.compact();
        return token;
    }

    /**
     * token解密
     * @param token
     * @return
     */
   public static Claims checkToken(String token){
        try {
            Claims claims = Jwts.parser()
                    // 设置签名的秘钥
                    .setSigningKey(jwtToken)
                    // 设置需要解析的jwt
                    .parseClaimsJws(token).getBody();
            return claims;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
   }
}
